package web.servlets;

import domain.Account;
import domain.Cart;
import domain.Item;
import persistence.CartDAO;
import persistence.Impl.CartDAOImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class RemoveItemFromCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";

    private String workingItemId;
    private Cart cart;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        workingItemId = req.getParameter("itemId");

        HttpSession session = req.getSession();
        cart = (Cart) session.getAttribute("cart");
        Account account = (Account) session.getAttribute("account");
        CartDAOImpl cartDAO = new CartDAOImpl();

        if(account!=null){
            cartDAO.removeItemByUserName(account.getUsername(),workingItemId);
        }

        Item item = cart.removeItemById(workingItemId);
        if(item == null){
            session.setAttribute("message","购物车内没有此物品");
            req.getRequestDispatcher(ERROR).forward(req,resp);
        }
        else {
            req.getRequestDispatcher(VIEW_CART).forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
